package com.school.edupoint.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.school.edupoint.config.EduContext;
import com.school.edupoint.model.Activity;

import com.school.edupoint.response.Result;
import com.school.edupoint.service.ActivityService;

import com.school.edupoint.vo.ActivityVO;
import com.school.edupoint.vo.MessageVO;
import com.school.edupoint.websocket.MyTextWebSocketHandler;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author
 * @date 2025/05/28 17:44
 */
@RestController
@RequestMapping("/api")
public class ActivityController {
    @Autowired
    private ActivityService activityService;
    @Autowired
    private EduContext eduContext;

    /**
     * 查询活动详情
     *
     * @param activityId
     * @return
     */
    @GetMapping("/activity/info/getInfo/{activityId}")
    public Result<Activity> getInfo(@PathVariable Long activityId) {
        return Result.success(activityService.getInfo(activityId));
    }


    /**
     * 活动分页
     *
     * @param param
     * @return
     * @throws Exception
     */
    @PostMapping("/activity/page")
    public Result<IPage<ActivityVO>> getActivityPage(@RequestBody Map<String, Object> param) throws Exception {
        String title = (String) param.get("title");
        int pageNum = (int) param.get("pageNum");
        int pageSize = (int) param.get("pageSize");
        System.out.println("当前第" + pageNum + "页");
        System.out.println("一页" + pageSize + "条数据");
        IPage<ActivityVO> activityIPage = activityService.selectPage(title, pageNum, pageSize);
        System.out.println("活动分页数据为：" + activityIPage);
        return Result.success(activityIPage);
    }

    /**
     * 增加、修改活动
     *
     * @param activityVO
     * @return
     */
    @PostMapping("/activity/save")
    public Result<ActivityVO> saveActivity(@RequestBody ActivityVO activityVO) {
        System.out.println("保存接口前端传过来数据：" + activityVO.toString());
        System.out.println("活动ID: " + activityVO.getId() + ", 类型: " + (activityVO.getId() != null ? activityVO.getId().getClass().getSimpleName() : "null"));

        // 检查是否为新增活动：通过查询数据库判断ID是否已存在
        boolean isNewActivity = false;
        if (activityVO.getId() != null) {
            try {
                Activity existingActivity = activityService.getInfo(activityVO.getId().longValue());
                isNewActivity = (existingActivity == null);
                System.out.println("数据库中查询活动ID " + activityVO.getId() + " 结果: " + (existingActivity != null ? "存在" : "不存在"));
            } catch (Exception e) {
                // 如果查询失败，假设是新增活动
                isNewActivity = true;
                System.out.println("查询活动失败，假设为新增活动: " + e.getMessage());
            }
        } else {
            isNewActivity = true;
            System.out.println("活动ID为null，确认为新增活动");
        }

        ActivityVO savedActivity = activityService.save(activityVO);

        // 如果是新增活动，则发送WebSocket通知给所有学生
        if (isNewActivity) {
            System.out.println("检测到新增活动，准备发送WebSocket通知");
            try {
                MessageVO notification = new MessageVO();
                notification.setTitle("新活动通知");
                notification.setContent("有新的活动发布了：" + activityVO.getTitle());
                notification.setMessageType("NEW_ACTIVITY");
                notification.setParam("{\"activityId\":\"" + savedActivity.getId() + "\",\"title\":\"" + activityVO.getTitle() + "\"}");

                System.out.println("准备发送的通知内容：" + notification.getTitle() + " - " + notification.getContent());

                // 向所有学生发送通知
                MyTextWebSocketHandler.broadcastToAllStudents(notification);
                System.out.println("已向所有学生发送新活动通知：" + activityVO.getTitle());
            } catch (Exception e) {
                System.err.println("发送WebSocket通知失败：" + e.getMessage());
                e.printStackTrace();
            }
        } else {
            System.out.println("检测到修改活动，不发送WebSocket通知，活动ID：" + activityVO.getId());
        }

        return Result.success(savedActivity);
    }

    /**
     * 上传活动图片
     */
    @PostMapping("/activity/uploadphoto")
    public Result<Map<String, String>> uploadphoto(
            @RequestParam("photo") MultipartFile photo,
            @RequestHeader(value = "Authorization", required = false) String token
    ) throws Exception {

        System.out.println("上传接口前端传输数据" + photo);
        String photoUrl = activityService.uploadPhoto(photo);
        Map<String, String> data = new HashMap<>();
        data.put("url", photoUrl);
        return Result.success(data);

    }


    /**
     * 根据ID删除活动
     *
     * @param
     * @return
     */
    @DeleteMapping("/activity/delete/{activityId}")
    public Result<Activity> deleteActivity(@PathVariable("activityId") Integer id) {
        activityService.delete(id);
        return Result.success(null);
    }


    /**
     * 导出活动信息
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/activity/export")
    public void export(HttpServletResponse response) throws IOException {
        activityService.exportActivitys(response);
    }

}